/*
Author:kermit
Email:455196886@qq.com
Company:http://dragontrail.com/
Creattime:2017-1-08
*/

//依赖jquery
var App = function() {
	var  app = this;
	//设置开发环境  development || test || production
	app.ENV = 'production';
	app.devUrl = 'http://hurtigruten.dragontrail.com';
	app.testUrl = 'http://hurtigruten.projects.dragontrail.cn';
	app.proUrl = 'http://hurtigruten.cn';
	//项目域名配置
	app.config = {
		domain:app.ENV=='development'? app.testUrl: app.proUrl,
		apiUrl:app.ENV=='development'? app.devUrl+'/api/': app.proUrl+'/api/'
	}
	console.log('config',app.config);
	//视频弹层
	app.LayerVideoInit = function(){
		$('body').on('click','[role="video"]',function(){
			var $this = $(this),
			video_url = $this.attr('video-url');
			var video_cover_tpl = 	'<div class="video-cover">'+
							'<div class="cover-bg"></div>'+
							'<div class="cover-box">'+
								'<div class="cover-box-inner">'+
									'<button class="btn btn-close"><i class="fa fa-close"></i></button>'+
									'<video controls="controls" width="100%" height="auto" autoplay="true" src="'+video_url+'"></video>'+
								'</div>'+
							'</div>'+
						'</div>';
			$('body').append(video_cover_tpl);
			$(".cover-box-inner video").get(0).play();
			$('html').addClass('un-scroll');
			var $videoCover = $('.video-cover'),
				$closeBtn = $videoCover.find('.btn-close'),
				$videoCoverBg = $videoCover.find('.cover-bg');
			$closeBtn.click(function(event) {
				$videoCover.remove();
				$('html').removeClass('un-scroll');
			});
			$videoCoverBg.click(function(event) {
				$videoCover.remove();
				$('html').removeClass('un-scroll');
			});
		})
	}()
	//手机菜单
	app.MobileMenuInit = function(){
		$("#openMenuBtn").click(function(event) {
			var $video = $("#homeVideo");
			console.log('$video',$video)
			if($video.length>0){
				if(!$video[0].paused){
					$video[0].pause();
				}
				$video.hide();
			}
			$("#mobileMenu").addClass('cover-menu-show');
			$('html').addClass('un-scroll');
			$("#mobileMenu").find('.btn-close').click(function(){
				if($video.length>0){ $video.show(); }
				$("#mobileMenu").removeClass('cover-menu-show');
				$('html').removeClass('un-scroll');
			})
		});
	}()
	//二维码弹层
	app.WechatQrcodeInit = function(){
		if(Common.screenWidth <= 1024){
			$('.wechat-box').click(function() {
				var $this = $(this),
					isOpen = $this.hasClass('show-qrcode');
				if(!isOpen){
					$this.addClass('show-qrcode');
				}else{
					$this.removeClass('show-qrcode');
				}
			});
		}
	}()
	//联系咨询表单
	app.CoverContentInit = function(){
		$(".content-btn").click(function(event) {
			var $coverContent = $('.cover-content'),
				$closeBtn = $coverContent.find('.btn-close');
				$submitBtn = $coverContent.find('.submit-btn');
			$coverContent.addClass('cover-content-show');
			$closeBtn.click(function(event) {
				$coverContent.removeClass('cover-content-show');
			});
			$submitBtn.click(function(){
				var surname = $coverContent.find("input[name='surname']").val(),
					email = $coverContent.find("input[name='email']").val(),
					mobile = $coverContent.find("input[name='mobile']").val(),
					destination = $coverContent.find("select[name='destination']").val(),
					experience = $coverContent.find("input[name='experience']").val(),
					other = $coverContent.find("input[name='other']").val();
					console.log('name',name,'mobile',mobile)
				$submitBtn.attr('disabled',true);
				if(mobile==""){
					Common.Toast('电话不能为空');
					$submitBtn.removeAttr('disabled');
				}else{
					$.ajax({
						type: 'POST',
						url: app.config.apiUrl+'post_data.json',
						data: {
							ajax_submit:1,
							surname:surname,
							email:email,
							mobile:mobile,
							destination:destination,
							experience:experience,
							other:other
						},
						dataType: 'json',
						success: function(data){
							console.log('data',data);
							$submitBtn.removeAttr('disabled');
							if(data.errcode==0){
								Common.Toast('提交成功！');
								$coverContent.removeClass('cover-content-show');
							}else{
								Common.Toast('提交失败！');
							}
					  	}
					});
					// setTimeout(function(){
					// 	//请求成功
					// 	$submitBtn.removeAttr('disabled');
					// },10000)
				}
			});
		});
	}
	/**
	*LoadMoreAjax 发送加载更多ajax请求
	@param 	isLoadingMore   boolean     列表元素
	@param 	listElemet    	string      列表元素
	@param 	postType    	string      分类类型
	@param 	props    		object      传递参数
		@param cursor string   下一页的开始节点，若为0,没有下一页
	@param 	callback    	function    回调函数
	@example
		App.LoadMoreAjax('destination',{next_cursor:,},function(data){})
	**/
	app.LoadMoreAjax = function(isLoadingMore,listElemet, postType, props, callback){
		var loading_tpl = 	'<div class="inline-loading">'+
								'<div class="inline-loading-inner clear-float">'+
									'<div class="loading-img float-left"><img src="/webs/hurtigruten/assets/images/loading.gif" alt=""></div>'+
									'<div class="loading-text float-left">加载中</div>'+
								'</div>'+
							'</div>';
		if(isLoadingMore){$(listElemet).after(loading_tpl);}
		app.isAjax = true;
		$.ajax({
			url: app.config.apiUrl+'mag.ajax_'+postType+'.list.json',
			data: props,
			dataType: 'json',
			success: function(data){
				app.isAjax = false;
				app.next_cursor = data.next_cursor;
				app.isAjaxEnd = app.next_cursor == 0 ? true : false;
				if(isLoadingMore){$('.inline-loading').remove();}
		  		callback && callback(data,postType);
		  	}
		});
	}
	//滚动加载更多
	/**
	*ScrollLoadMoreInit 滚动加载更多
	@param 	listElemet    	string      列表元素
	@param 	postType    	string      分类类型
	@param 	callback    	function    回调函数
	@example
		App.ScrollLoadMoreInit(listElemet,'destination',function(data){})
	**/
	app.ScrollLoadMoreInit = function(listElemet,postType,callback){
		//发送Ajax的状态
		app.isAjax = false;
		//Ajax是否有数据
		app.isAjaxEnd = false;
		//分页节点
		app.next_cursor = next_cursor;
		app.isAjaxEnd = next_cursor == 0 ? true : false;
		if(!app.isAjaxEnd){
			$(window).on('scroll',function(){
				var scrollTop = $(window).scrollTop(),
					windowHeight = $(window).height(),
					documentHeight = $(document).height(),
					isScrollFooter = scrollTop + windowHeight == documentHeight;
				if(isScrollFooter && !app.isAjax && !app.isAjaxEnd){
					app.LoadMoreAjax(true,listElemet, postType, {cursor:app.next_cursor}, function(data){
						callback && callback(data);
					});
				}
			});
		}
	}
	//搜索初始化
	app.SearchInit = function(){
		app.serchType = 'route-search';
		$(".switch-btn").click(function(){
			var $this = $(this),
				serchType = $this.data('type'),
				$serchBox = $this.parents('.menu-header').find('.search-box'),
				$searchBtn = $serchBox.find('.search-btn');
			app.serchType = serchType;
			$searchBtn.attr('data-type',serchType);
			$this.addClass('btn-active').siblings('.switch-btn').removeClass('btn-active');
		});
		$(".search-btn").click(function(event) {
			var $this = $(this),
				serchType = $this.data('type'),
				$serchBox = $this.parents('.search-box'),
				searchKeword = $serchBox.find('input').val();
			if(searchKeword !== ''){
				window.location.href = '/'+serchType+'/'+searchKeword;
			}
		});
		$('.search-input').focus(function(event) {
			document.onkeydown = function (e) {
		      	if (!e) e = window.event;
		      	if ((e.keyCode || e.which) == 13) {
		        	$('.search-btn[data-type='+app.serchType+']').trigger('click');
		      	}
		    }
		});
	}();
	//点赞数据初始化
	app.GiveThumbInit = function(){
		var like_ids = Common.GetCookie('post_like_ids');
			(like_ids == null||like_ids == undefined) && (like_ids = "");
			like_ids = unescape(like_ids)
		//console.log('like_ids',like_ids)
		var arr = (like_ids.length > 0) ? (like_ids.split(",")) : []
		var _isDianzan = false;
		for(var i=0,len=arr.length;i<len;i++) {
			var $btnThumb = $('.btn-thumb[data-likeid='+arr[i]+']'),
				$comTipBox = $('.com-tip-box[data-id="'+arr[i]+'"]');
			$btnThumb.addClass('active').attr('disabled',true);
			$comTipBox.attr('likedClass','active');
		}
	}
	//点赞
	app.GiveThumb = function(){
		app.GiveThumbInit();
		$('body').on('click','.btn-thumb',function(){
			var $this = $(this),
				likeid = $this.data('likeid');
				role = $this.data('role');
			$this.attr('disabled',true);
			$.ajax({
				url: app.config.apiUrl+'post_data.json',
				data: {ajax_like_id:likeid},
				dataType: 'json',
				success: function(data){
					console.log('data',data)
					$this.removeAttr('disabled');
					if(data.errcode==0){
						var like_ids = Common.GetCookie('post_like_ids');
							(like_ids == null||like_ids == undefined) && (like_ids = "");
							like_ids = unescape(like_ids)
						console.log('like_ids',like_ids)
						like_ids += data.return_id +",";
						Common.SetCookie('post_like_ids',like_ids,1);
						var $btnThumb = $('.btn-thumb[data-likeid='+data.return_id+']'),
							$comTipBox = $('.com-tip-box[data-id="'+data.return_id+'"]');
						$btnThumb.addClass('active').attr('disabled',true);
						$btnThumb.find('.thumb-num').html(data.like_count);
						$comTipBox.attr('data-likecount',data.like_count).attr('likedClass','active').data('likecount',data.like_count);
						Common.Toast('点赞成功！');
					}
			  	}
			});
		})
	}();
	//订阅邮件
	app.BookEmail = function(){
		//邮件订阅
		$("#eamilBtn").click(function(event) {
			console.log('test')
			var $this = $(this),
				eamil  = $this.siblings('input[type=email]').val();
			if(/\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+/.test(eamil)){
				$.ajax({
					type: 'POST',
					url: 'http://hurtigruten.dragontrail.com/api/post_data.json',
					data: {ajax_email:1,email:eamil},
					dataType: 'json',
					success: function(data){
						//console.log('data',data)
						if(data.errcode==0){
							Common.Toast('订阅成功！');
						}else if(data.errcode == 2){
							Common.Toast('已订阅！');
						}else{
							Common.Toast('订阅失败！');
						}
				  	}
				});
			}else{
				Common.Toast('请填写正确的邮箱');
			}
		});
		$('.footer input[type=email]').focus(function(event) {
			document.onkeydown = function (e) {
		      	if (!e) e = window.event;
		      	if ((e.keyCode || e.which) == 13) {
		    		$("#eamilBtn").trigger('click');
		      	}
		    }
		});
	}();
	//社交分享
	app.shareInit = function(){
		var qrcode = new QRCode(document.getElementById("qrcode"), {
			width : 158,
			height : 158
		});
		$('body').on('click','.share_box a',function(){
			var $this = $(this),
				share_type = $this.data('cmd'),
				$shareBox = $this.parents('.share-box'),
				share_option = {
				    title :$shareBox.data('text'),
				    content :$shareBox.data('desc'),
				    url :app.config.domain+$shareBox.data('url'),
				    pic :$shareBox.data('pic')
				};
			//console.log('share_option',share_option);
			if(share_type !== 'weixin'){
				share_option.url = share_type=='tsina' ? share_option.url.split('#')[0] : share_option.url;
				//分享地址
				var share_request = {
					qzone:'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url='+share_option.url+'&title='+share_option.title+'&pics='+share_option.pic+'&summary='+share_option.content,
					tsina:'http://service.weibo.com/share/share.php?url='+share_option.url+'&title='+share_option.title+'&pic='+share_option.pic+'&searchPic=false',
					sqq:'http://connect.qq.com/widget/shareqq/index.html?url='+share_option.url+'&title='+share_option.title+'&pics='+share_option.pic+'&summary+'+share_option.content,
					weixin:'http://qr.liantu.com/api.php?text='+share_option.url //接受URL返回图片
				}
				window.open(share_request[share_type]);
			}else{
				qrcode.makeCode(share_option.url);
				$('#shareCover').addClass('share-cover-show');
				$('html').addClass('.un-scroll');
				$('#shareCover').find('.btn-close').click(function(){
					$('#shareCover').removeClass('share-cover-show');
					$('html').removeClass('.un-scroll');
				});
			}
		});
	}();
	app.Init = function() {
		app.CoverContentInit();
		$('.video-container').click(function(event) {
			var $this = $(this),
				$video = $this.find('video')
				video = $video[0];
			if(video.paused){
				$video.attr('controls',true);
				$this.addClass('playing');
				video.play();
			}else{
				video.pause();
				$video.removeAttr('controls');
				$this.removeClass('playing');
			}
		});
		$(window).on('scroll',function(){
			var scrollTop = $(window).scrollTop();
			if(scrollTop>600){
				$("#gotop").addClass('gotop-show');
			}else{
				$("#gotop").removeClass('gotop-show');
			}
		});
		$("#gotop").click(function(event) {
			$('body,html').animate({scrollTop:0},500);
			return false;
		});
		console.log('app init');
	}
}
var App = new App();
App.Init();